package com.itobase.statusDetect.Controller;

import com.itobase.statusDetect.Model.Teaching;
import com.itobase.statusDetect.Model.Time;
import com.itobase.statusDetect.Repository.TeachingRepository;
import com.itobase.statusDetect.Repository.TimeRepository;
import com.itobase.statusDetect.Service.TimeService;
import com.itobase.statusDetect.Util.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.InvalidParameterException;
import java.util.List;
import java.util.Map;

/**
 * @author htyu
 * @date 2019/2/24
 */

@RestController
@RequestMapping("time")
public class TimeController {

    @Autowired
    TimeRepository timeRepository;

    @Autowired
    TimeService timeService;

    @Autowired
    TeachingRepository teachingRepository;

    /**
     * 新建学期
     * @param time
     * @return
     */
    @PostMapping("create")
    public Message create(@RequestBody Time time){
        return timeService.create(time);
    }


    /**
     * 获取学期列表（可根据学期筛选）
     * @param keyword
     * @return
     */
    @GetMapping("list")
    public Message getList(@RequestParam(required = false) String keyword){
        return Message.success(timeService.getList(keyword));
    }


    /**
     * 批量删除学年
     * @param map
     * @return
     */
    @DeleteMapping("delete")
    public Message deleteTime(@RequestBody Map<String, List<String>> map){
        List<Teaching> list;
        List<String> ids = map.get("ids");
        for(String id : ids){
            list = teachingRepository.findByTimeID(id);
            if(list.size()==0) {
                timeRepository.deleteById(id);
            }else{
                return Message.error("此学期有课程安排，您不能删除此学期");
            }
        }
        return Message.success("删除成功");
    }

    @GetMapping("detail")
    public Message getDetail(@RequestParam String timeID){
        try {
            Time time = timeRepository.findById(timeID).orElseThrow(() -> new InvalidParameterException("该学年不存在"));
            return Message.success(time);
        }catch (InvalidParameterException e){
            return Message.error("该学年不存在");
        }
    }

    @PutMapping("update")
    public Message updateTime(@RequestBody Time time){
        return timeService.update(time);
    }


}
